package com.baiytfp.hf.HFDataExchange.action.dao;

import com.baiytfp.hf.baiytfp.common.db.DBManager;
import com.baiytfp.hf.baiytfp.framework.base.BaseDao;
import com.baiytfp.hf.baiytfp.framework.model.state.YesOrNo;
import com.baiytfp.hf.baiytfp.hfutils.HFDBHelper;
import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.model.table.Tree;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Repository
public abstract class TreeDAOImpl extends BaseDao {
    /**
     * 对功能树子节点排序, 并返回最后的序号+1
     */
    public int setChildNodeOrder(List list, long orderNum, String seqCode) throws Exception {

        Connection connection = null;
        List params = null;
        int i = 1;

        try {
            connection = DBManager.getConnection();
            DBManager.beginTransaction(connection);

            StringBuffer updateSql = new StringBuffer();
            updateSql.append("update " + TableName.TREE + " set NODE_ORDER=? where id=?");

            Iterator<Tree> it = list.iterator();
            while(it.hasNext()){
                Tree treeVO = it.next();
                if(!seqCode.equals(treeVO.getTree_code())){  // 不对需要操作的结点排序
                    if(i == orderNum){
                        i++;
                    }
                    params = new ArrayList();
                    params.add(i + "");
                    params.add(treeVO.getId() + "");

                    HFDBHelper.executeSql(connection, updateSql.toString(), params.toArray());
                    i++;
                }
            }

            DBManager.commitTransaction(connection);
        } catch (SQLException sqle) {
            DBManager.rollbackTransaction(connection);
        } finally {
            DBManager.close(connection);
        }
        return i;
    }

    // 更新子结点的父结点
    public abstract long updateChildrenSeqCode(String seqCode, String oldSeqCode, int deepDiff, String treeType) throws Exception;

	public Tree getNodeInfo(String treeCode, String treeType,Connection conn) throws Exception {
		StringBuffer sWhere = new StringBuffer();
		List params = new ArrayList();

		sWhere.append(" where TREE_TYPE = ? and TREE_CODE=?  ");
		params.add(treeType);
		params.add(treeCode);

		return HFDBHelper.read(conn,TableName.TREE, sWhere.toString(), Tree.class, params.toArray());
	}

	public boolean delByTreeCode(String treeCode,int treeType) throws Exception {
		StringBuffer sql = new StringBuffer().append("UPDATE hfdataexchange_tree t SET t.children_number = t.children_number - 1 ")
				.append("WHERE t.tree_type = ? AND t.children_number >= 0 AND t.tree_code = ( ")
				.append("	SELECT parent_tree_code FROM ( ")
				.append("		SELECT t2.parent_tree_code FROM hfdataexchange_tree t2 WHERE t2.tree_code = ? AND t2.tree_type = ? ")
				.append("	) sel_all ")
				.append(")");
		long rs = HFDBHelper.executeSql(sql.toString(), treeType, treeCode, treeType);

//		StringBuffer sql = new StringBuffer().append(" update ").append(TableName.TREE)
//				.append(" set children_number=children_number-1 where  children_number > 0 and ")
		rs += HFDBHelper.delete(TableName.TREE, " where TREE_TYPE = ? and TREE_CODE like ?  ", new Object[]{treeType + "",treeCode + "%" });
		return rs>=0;
	}

	public Tree add(Tree tree) throws Exception {
		if(!"-1".equals(tree.getParent_tree_code())){

			Tree parentTree = getTreeInfo(tree.getParent_tree_code(), tree.getTree_type());
			tree.setNode_deep(parentTree.getNode_deep()+1);//深度为父深度+1
			parentTree.setChildren_number(parentTree.getChildren_number() + 1);// 父结点孩子数加+1
			update(parentTree);
		}else{
			tree.setNode_deep(1);//深度为1
		}
		//先添加树结点
		long rs = HFDBHelper.add(TableName.TREE, tree);
		return rs>0 ? tree : null;
	}

	public Tree update(Tree tree) throws Exception {
		Long rs = HFDBHelper.update(TableName.TREE, " where id=? ", tree, tree.getId() );
		return rs>0 ? tree : null;
	}

	public Tree getTreeInfo(String treeCode,int treeType) throws Exception {
		return HFDBHelper.read(TableName.TREE, " where TREE_TYPE = ? and TREE_CODE=?  ", Tree.class, new Object[]{ treeType, treeCode});
	}

}
